<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../extjs_all/resources/css/ext-all.css"></link>
<script type="text/javascript" src="../../extjs_all/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../../extjs_all/ext-all.js"></script>
<script type="text/javascript" src="../../extjs_all/source/locale/ext-lang-zh_CN.js"></script>

<script type="text/javascript">
Ext.onReady(function(){
	Ext.QuickTips.init();	//初始化Ext.QuickTips，以使得tip提示可用
	Ext.form.Field.prototype.msgTarget='side';		//提示后面显示图片标记
	/**
	 * JS中，当有对象需要引用的时候，必须在引用之前就定义，否则的话，需要在constructor中初始化
	 */
	UsersFormPanel = Ext.extend(Ext.form.FormPanel,{
		constructor:function(){
			UsersFormPanel.superclass.constructor.call(this,{
				labelWidth:80,
				defaults:{anchor:'90%'},		//自动拉伸
				baseCls:'x-plain',			//强制设置窗体颜色
				defaultType:'textfield',
				bodyStyle:'padding:8px',
				items:[{
					xtype:'hidden',
					name:'id'
				},{
					fieldLabel:'用户登录名',
					allowBlank:false,
					name:'loginname',
					maxLength:50
				},{
					fieldLabel:'用户名称',
					allowBlank:false,
					name:'username',
					maxLength:50
				},{
					fieldLabel:'密码',
					allowBlank:false,
					name:'password',
					maxLength:50
				},{
					fieldLabel:'Email',
					name:'email',
					maxLength:50
				},{
					fieldLabel:'电话',
					name:'phone',
					maxLength:50
				},{
						store:new Ext.data.SimpleStore({
							fields:['value','status'],
							data:[['1','激活'],['2','挂起']]
						}),
					fieldLabel:'状态',
					xtype:'combo',
					triggerAction:'all',
					valueField:'value',
					displayField:'status',
					mode:'local',
					name:'key'
					//hiddenName:"parentId",	//当数据为本地数据的时候,可以通过键值对来获得下拉框的值,远程暂时没有解决方案
					
//						//远程调用,查询到数据库中的数据,然后显示
// 					store:rankData = new Ext.data.JsonStore({  
// 						root:'list',
// 			            proxy : new Ext.data.HttpProxy({  
// 	                        url : 'dictparent.action'  
// 	                    }),  
// 	                    fields:['dictName','parentId']
// 	        		}) 
				},{
					store:new Ext.data.SimpleStore({
						fields:['value','status'],
						data:[['1','宋体'],['2','楷体'],['3','魏碑'],['4','黑体']]
					}),
				fieldLabel:'部门',
				xtype:'combo',
				triggerAction:'all',
				valueField:'value',
				displayField:'status',
				mode:'local',
				name:'key'
				//hiddenName:"parentId",	//当数据为本地数据的时候,可以通过键值对来获得下拉框的值,远程暂时没有解决方案
				
//					//远程调用,查询到数据库中的数据,然后显示
//					store:rankData = new Ext.data.JsonStore({  
//						root:'list',
//			            proxy : new Ext.data.HttpProxy({  
//	                        url : 'dictparent.action'  
//	                    }),  
//	                    fields:['dictName','parentId']
//	        		}) 
			}]
			})
		},
		getValues:function(){
			//alert(Ext.util.JSON.encode(this.form.getValues()));
			if(this.getForm().isValid()){
				this.fireEvent("submit",this,this.form.getValues());
			}else{
				throw Error("表单验证未通过！");		//抛出异常，在调用getValues函数的地方捕获并提示
			}
			//alert(this.getForm().getValues());
			return new Ext.data.Record(this.getForm().getValues());
		},
		setValues:function(re){
			this.getForm().loadRecord(re);
		},
		reset:function(){
			this.getForm().reset();
		}
	});
	/**
	 * 弹出编辑窗口类，提供创建和修改使用
	 */
	 UserWindow = Ext.extend(Ext.Window,{
		//将FormPanel放到Window中
		form:null,
		constructor:function(){
			this.form = new UsersFormPanel(),
			UserWindow.superclass.constructor.call(this,{
				plain:true,			//通过背景颜色来渲染窗口颜色
				width:500,
				modal:true,			//只能操作当前窗口
				closeAction:'hide',
				items:this.form,
				buttons:[{
						text:'确定',
						handler:this.onsubmit,
						scope:this
					},{
						text:'取消',
						handler:this.oncanel,
						scope:this
					}]
			});
			this.addEvents("submit");
		},	
		close:function(){
			this.form.reset();
			this.hide();
		},
		onsubmit:function(){
			try{
				this.fireEvent("submit",this,this.form.getValues());
				//获得Form提交后的ID,如果为空,表示添加,否则为修改
					var id = Ext.util.JSON.encode(this.form.getValues().data.id);
				Ext.Ajax.request({
					url:'savedata.action',
					params:{
						content:"["+Ext.util.JSON.encode(this.form.getValues().data)+"]"
					},
					//提交成功后,处理一些事务
					 success : function(response){
						//alert(response.responseText);
						var value = Ext.util.JSON.decode(response.responseText);
						var cc =new Ext.data.Record.create(['id','itemId','dictName','value1','value2','remark','parentId']);
						var cdata = new cc(value.dataDict);
						//将数据插入到第一行,并删除store最后一行
						var gridStore = Ext.getCmp('dataDictGrid').store;
						var c = id.replace('"','').replace('"','');		//去除不必要的符号
						if(""==c){
							if(gridStore.getCount() == 20){
								gridStore.insert(0,cdata);
								gridStore.remove(gridStore.getAt(gridStore.getCount()-1));
							}else{
								//gridStore.add(cdata);
								gridStore.insert(0,cdata);
							}
						}else{
							var selectRe = Ext.getCmp('dataDictGrid').getSelectionModel().getSelected();			//获得Grid选择的record
							var data = selectRe.data;
							//alert(Ext.util.JSON.encode(data));		//获得Record的数据，然后转换成JSON打印
							//遍历record.data,修改原record的值
							for(var i in data){
								selectRe.set(i,cdata.get(i));
							}
							selectRe.commit();
						}
					}  
				});
			}catch(err){
				Ext.Msg.alert('提示',err);
				return ;
			}
			this.close();
		},
		oncanel:function(){
			this.close();
		}
	}) ;

	/*********************************/
	//添加
	InsertUsersWindow = Ext.extend(UserWindow,{
		title:'添加数据'
	});
	//修改
	UpdateUsersWindow = Ext.extend(UserWindow,{
		title:'修改数据',
		load:function(re){
			this.form.setValues(re);
		}
	});
	/**
	 * 数据显示Grid
	 */
	UserListGrid = Ext.extend(Ext.grid.GridPanel,{
		insertUsers:new InsertUsersWindow(),
		updateUsers:new UpdateUsersWindow(),
		constructor:function(){
			this['store']= new Ext.data.JsonStore({
				root:'list',
				totalProperty:'cnt',
				url:'finduserslistbyrole.action',
			fields:[{
						name:'id', type: 'int'
					},'username','loginname','email','phone','createtime','status','deptid','rolename','deptname']
			}),
			//ToolBar
			this['toolBar'] = new Ext.Toolbar({
				
				items:[{
					text:'新增',
					icon:'../../imgs/add.gif',
					cls: "x-btn-text-icon" ,		//自定义图片
					handler:function(){
						this.insertUsers.show();
					},
					scope:this
				},{
					text:'修改',
					icon:'../../imgs/edit.gif',
					cls: "x-btn-text-icon" ,		//自定义图片
					handler:function(){
						this.updateUsers.show();						//首先,修改窗体显示
						try{											//然后将用户选择的数据回写到窗体上	
							this.updateUsers.load(this.getSelected());
						}catch(err){
							Ext.Msg.alert('提示',err.description);
							this.updateUsers.close();
						}
					},
					scope:this
				},{
					text:'删除',
					icon:'../../imgs/delete.gif',
					cls: "x-btn-text-icon" ,		//自定义图片
					//hidden :id == id.replace(c) ? false : true,
//						handler:function(){
//							this.onRemove
//							Ext.Msg.confirm('提示','是否删除？',this.onRemove,this);
//						},
					handler:function(){
						this.onRemove()	
					},
					scope:this
				},{
					text:'查看用户权限',
					icon:'../../imgs/delete.gif',
					cls: "x-btn-text-icon" ,		//自定义图片
					handler:function(){
						this.onRemove()	
					},
					scope:this
				},{
					text:'为用户设置权限',
					icon:'../../imgs/delete.gif',
					cls: "x-btn-text-icon" ,		//自定义图片
					handler:function(){
						this.onRemove()	
					},
					scope:this
				}]
			})
			
			UserListGrid.superclass.constructor.call(this,{
				id:'userListGrid',
				title:'用户信息列表',
				renderTo:'userListGrid',
				height:600,
				autoExpandColumn:8,
				//height : Ext.get('dataDictGrid').getHeight(), 
				sm:new Ext.grid.CheckboxSelectionModel({
					singleSelect:true
				}),
				tbar:this.toolBar,
				bbar:new Ext.PagingToolbar({
					pageSize:20,
					store:this.store,
					// plugins: filters,
					displayInfo:true,
					displayMsg:'第{0}条到{1}条，共{2}条',
					emptyMsg:'没有记录'
				}),
				columns:[
				         	new Ext.grid.CheckboxSelectionModel({
				         		singleSelect : true
				         	}),{
								header:'用户名称',
								width:200,
								dataIndex:'username',
								sortable:true
							},{
								header:'登陆名',
								width:200,
								dataIndex:'loginname',
								sortable:true
							},{
								header:'角色',
								width:200,
								dataIndex:'rolename',
								sortable:true
							},{
								header:'邮箱',
								width:200,
								dataIndex:'email',
								sortable:true
							},{
								header:'电话',
								width:200,
								dataIndex:'phone',
								sortable:true
							},{
								header:'创建时间',
								width:200,
								dataIndex:'createtime',
								renderer:function(val){
									if(val!=null)
									 return val.split('T')[0]
								},
								sortable:true
							},{
								header:'部门',
								width:200,
								dataIndex:'deptname',
								sortable:true
							},{
								header:'状态',
								renderer:function(val){
									if(val!=null){
										if(val == 1){
											return "激活";
										}else{
											return "挂起";
										}
									}
								},
								dataIndex:'status',
								sortable:true
							}]
			});
			this.getStore().load({
				url:'finduserslistbyrole.action',
				params:{start:0,limit:20}
			});
			//this.insertDataDict.on('submit',this.onsubmit,this);		//为可视化窗口:insertWin添加事件(事件名称，调用的函数，scope)
		Ext.Ajax.on('requestcomplete',this.requestFunction,this);
	},
	
	//在插入数据的时候,返回的ID需要重新加载到insertdata对象中,这样就同数据库一样了,根据ID可以修改和删除数据
	requestFunction:function(conn,response,options){
// 			var c = Ext.util.JSON.decode(response.responseText);
// 			alert(c.list)
//			var res = c.list;
//			for(var i = 0;i<res.length;i++){
//				var rc = res[i];
//			}
	}
	});
	
	new UserListGrid();
});
</script>
<title>用户列表信息</title>
</head>
<body>
<div id="userListGrid"></div>
</body>
</html>